package com.fly.server.config;

import com.fly.server.handler.CustomAccessDeniedHandler;
import com.fly.server.handler.EntryPointUnauthorizedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName WebSecurityConfiguration
 * @Description TODO
 * @Author Fly
 * @Version
 * @Date 2020/1/4 20:53
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;

    private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;

    public WebSecurityConfiguration(EntryPointUnauthorizedHandler entryPointUnauthorizedHandler, PasswordEncoder passwordEncoder) {
        this.entryPointUnauthorizedHandler = entryPointUnauthorizedHandler;
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("admin").password(passwordEncoder.encode("123456")).roles("USER");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().disable();
        http.authorizeRequests().anyRequest().authenticated()
                .and().formLogin();
       http.exceptionHandling().authenticationEntryPoint(entryPointUnauthorizedHandler);
    }

    /**
     * 认证管理器，当要使用密码（password）授权类型时必须注入
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
